# -*- coding: utf-8 -*-
from rest_framework import serializers
from .models import Department


class DepartmentSerializer(serializers.ModelSerializer):
    """
    部门序列化器
    """
    full_name = serializers.ReadOnlyField()
    manager_name = serializers.CharField(source='manager.username', read_only=True)
    parent_name = serializers.CharField(source='parent.name', read_only=True)
    children_count = serializers.SerializerMethodField()
    
    class Meta:
        model = Department
        fields = ['id', 'name', 'description', 'parent', 'parent_name', 
                  'manager', 'manager_name', 'is_active', 'full_name', 
                  'children_count', 'created_time', 'updated_time']
        read_only_fields = ['id', 'created_time', 'updated_time']
    
    def get_children_count(self, obj):
        """获取子部门数量"""
        return obj.children.filter(is_active=True).count()
    
    def validate(self, attrs):
        """验证数据"""
        # 检查是否形成循环引用
        parent = attrs.get('parent')
        if parent and self.instance:
            current = parent
            while current:
                if current.id == self.instance.id:
                    raise serializers.ValidationError('不能将自己或子部门设为上级部门')
                current = current.parent
        return attrs


class DepartmentTreeSerializer(serializers.ModelSerializer):
    """
    部门树形结构序列化器
    """
    children = serializers.SerializerMethodField()
    manager_name = serializers.CharField(source='manager.username', read_only=True)
    
    class Meta:
        model = Department
        fields = ['id', 'name', 'description', 'manager', 'manager_name', 
                  'is_active', 'children']
    
    def get_children(self, obj):
        """获取子部门"""
        children = obj.children.filter(is_active=True)
        return DepartmentTreeSerializer(children, many=True, context=self.context).data


class DepartmentOptionSerializer(serializers.ModelSerializer):
    """
    部门选项序列化器（用于下拉选择）
    """
    label = serializers.CharField(source='name', read_only=True)
    value = serializers.IntegerField(source='id', read_only=True)
    
    class Meta:
        model = Department
        fields = ['value', 'label']